var standardElements =
[
	{
		label: 'Yes/No',
		dojoType: 'dijit.form.CheckBox',
		dataType: 'bit'
	},
	{
		label: 'Number',
		dojoType: 'dijit.form.NumberSpinner',
		dataType: 'int'
	},
	{
		label: 'Line Text',
		dojoType: 'dijit.form.ValidationTextBox',
		dataType: 'char'
	},
	{
		label: 'Paragraph Text',
		dojoType: 'dijit.form.SimpleTextarea',
		dataType: 'text'
	}
];

var advancedElements =
[
	{
		label: 'Date & Time',
		dojoType: ['dijit.form.DateTextBox', 'dijit.form.TimeTextBox'],
		dataType: 'datetime'
	},
	{
		label: 'Date',
		dojoType: 'dijit.form.DateTextBox',
		dataType: 'date'
	},
	{
		label: 'Time',
		dojoType: 'dijit.form.TimeTextBox',
		dataType: 'time'
	}
];

var initBuilder = function()
{	
	standardElementsSource = new dojo.dnd.Source('standardElementsContainer', {singular: true, copyOnly: true, creator: sourceFormNodeCreator});
	standardElementsSource.insertNodes(false, standardElements);
	
	advancedElementsSource = new dojo.dnd.Source('advancedElementsContainer', {singular: true, copyOnly: true, creator: sourceFormNodeCreator});
	advancedElementsSource.insertNodes(false, advancedElements);
	
	newClassTarget = new dojo.dnd.Source('newClassTargetContainer', {singular: true, creator: targetFormNodeCreator});
	dojo.style(newClassTarget.node, {height: 'auto', paddingTop: '15px', paddingBottom: '15px', paddingLeft: '5px', paddingRight: '5px', border: '1px solid #999', background: '#eee'});
	
	standardElementsSource.checkAcceptance = advancedElementsSource.checkAcceptance = function(){return false;};
	dojo.subscribe("/dnd/drop", function(){
		resetSelections();
		dojo.dnd.manager().canDrop(false);
	});
	
	//this is buggy
	/*
	dojo.connect(standardElementsSource, "_addItemClass", function(node, type)
	{
		switch(type)
		{
			case 'Anchor':
			case 'Selected':
				// the item was selected
				
				copyElement(standardElementsSource, node);
				break;
		}
	});
	
	dojo.connect(advancedElementsSource, "_addItemClass", function(node, type)
	{
		switch(type)
		{
			case 'Anchor':
			case 'Selected':
				// the item was selected
				
				copyElement(advancedElementsSource, node);
				break;
		}
	});
	*/
	
}

var copyElement = function(source, node)
{
	var id = node.id;
	var item = source.getItem(id);
	
	newClassTarget.insertNodes(false, [item.data]);
	source.selectNone();
}

var resetSelections = function()
{
	standardElementsSource.selectNone();
	advancedElementsSource.selectNone();
	newClassTarget.selectNone();
	
}
var sourceFormNodeCreator = function(oldItem, hint)
{
	var item = 
	{
		label: oldItem.label,
		dataType: oldItem.dataType,
		dojoType: oldItem.dojoType
	};
	var div = document.createElement("div");
	var label = document.createElement("dt");
	label.innerHTML = item.label;
	div.appendChild(label);
	div.appendChild(document.createElement("br"));
	
	if(!(item.dojoType instanceof Array))
	{
		var dojoTypes = [item.dojoType];
	}
	else
	{
		var dojoTypes = item.dojoType;
	}
	var fieldContainer = document.createElement("dd");
	for(var i in dojoTypes)
	{
		var field = eval('new ' + dojoTypes[i] + '()');
		field.placeAt(fieldContainer);
	}
	div.appendChild(fieldContainer);
	//div.appendChild(field.node);
	if(hint == 'avatar')
	{
		
	}
	else
	{
		
	}
	item.id = item.id? item.id : null;
	
	return {node: div, data: item};
}
var targetFormNodeCreator = function(oldItem, hint)
{
	var item = 
	{
		label: oldItem.label,
		dataType: oldItem.dataType,
		dojoType: oldItem.dojoType
	};
	
	var div = document.createElement("div");
	
	var label = document.createElement("dt");
	label.innerHTML = item.label  + ' (click to edit)';
	labelValue = new dijit.InlineEditBox({editor: 'dijit.form.TextBox', autoSave: true}, label);
	labelValue.onChange = function(){
		item.label = this.value;
		;updateClass();};
	div.appendChild(label);
	div.appendChild(document.createElement("br"));
	
	if(!(item.dojoType instanceof Array))
	{
		var dojoTypes = [item.dojoType];
	}
	else
	{
		var dojoTypes = item.dojoType;
	}
	var fieldContainer = document.createElement("dd");
	for(var i in dojoTypes)
	{
		var field = eval('new ' + dojoTypes[i] + '()');
		field.placeAt(fieldContainer);
	}
	div.appendChild(fieldContainer);
	
	//div.appendChild(field.node);
	if(hint != 'avatar')
	{
		var fieldToolBar = document.createElement("div");
		div.appendChild(fieldToolBar);
		var deleteButton = new dijit.form.Button({label: 'Delete', iconClass: "dijitEditorIcon dijitEditorIconDelete"});
		deleteButton.onClick = function()
		{
			deleteElement();
		};
		deleteButton.placeAt(fieldToolBar);
	}
	else
	{
		// do avatar stuff
	}
	item.id = item.id? item.id : null;
	
	return {node: div, data: item};
}

var deleteElement = function()
{
	newModalConfirm({title: 'Are You Sure?', content: 'Are you sure you want to do that?<BR />Deleting this field will also delete any data preiously saved in this field when you save this form!', execute:
		function()
		{
			newClassTarget.deleteSelectedNodes();
		}
	});
}

var OrderedIter = function (container, f, o){
	  // similar to:
	  // container.forInItems(f, o);
	  // but iterates in the listed order

	  o = o || dojo.global;
	  container.getAllNodes().forEach(function(node){
	    var id = node.id;
	    f.call(o, container.getItem(id), id, container);
	  });
	}


var updateClass = function()
{
	var newClass =
	{
		id: dojo.byId('classId') ? dojo.byId('classId').value : null,
		name: dijit.byId('className').value,
		fields: []
		
	};
	
	OrderedIter(newClassTarget, function(obj, id, container){newClass.fields.push(obj.data);})

	$jsonString = dojo.toJson(newClass, true);
	//alert($jsonString);
	dojo.byId('classTypeData').value = $jsonString;
}
var saveClass = function()
{
	updateClass();
	dojo.byId('classTypeForm').submit();
}

var loadClass = function()
{
	dojo.byId('className').innerHTML = classTypeData.name;
	dijit.byId('className').value = classTypeData.name;
	dojo.byId('classId').value = classTypeData.id;
	
	for(field in classTypeData.fields)
	{
		for(templateField in standardElements)
		{
			if(standardElements[templateField].dataType == classTypeData.fields[field].dataType)
			{
				classTypeData.fields[field].dojoType = standardElements[templateField].dojoType;
			}
		}
		
		for(templateField in advancedElements)
		{
			if(advancedElements[templateField].dataType == classTypeData.fields[field].dataType)
			{
				classTypeData.fields[field].dojoType = advancedElements[templateField].dojoType;
			}
		}
	}
	newClassTarget.insertNodes(false, classTypeData.fields);
}